/**
 * 数据库迁移模块
 * 处理数据库结构的版本迁移
 */
export class DatabaseMigration {
  constructor(dbCore) {
    this.db = dbCore;
    this.currentVersion = 1; // 当前数据库版本
  }

  /**
   * 执行所有待执行的迁移
   */
  migrate() {
    try {
      const currentVersion = this.getDatabaseVersion();
      console.log(`📚 当前数据库版本: ${currentVersion}`);

      if (currentVersion < this.currentVersion) {
        console.log(`📚 开始数据库迁移: ${currentVersion} -> ${this.currentVersion}`);
        this.executeMigration(currentVersion);
        this.setDatabaseVersion(this.currentVersion);
        console.log('📚 数据库迁移完成');
      } else {
        console.log('📚 数据库已是最新版本，无需迁移');
      }
    } catch (error) {
      console.error('❌ 数据库迁移失败:', error.message);
      throw error;
    }
  }

  /**
   * 获取当前数据库版本
   */
  getDatabaseVersion() {
    try {
      const result = this.db.prepare("PRAGMA user_version").get();
      return result.user_version || 0;
    } catch (error) {
      console.warn('⚠️ 获取数据库版本失败，默认为版本 0');
      return 0;
    }
  }

  /**
   * 设置数据库版本
   */
  setDatabaseVersion(version) {
    this.db.exec(`PRAGMA user_version = ${version}`);
  }

  /**
   * 执行迁移
   */
  executeMigration(fromVersion) {
    const migrationTransaction = this.db.transaction(() => {
      // 版本 0 -> 1: 添加新的HTTP版本字段
      if (fromVersion < 1) {
        this.migrateToVersion1();
      }

      // 未来的迁移可以在这里添加
      // if (fromVersion < 2) {
      //   this.migrateToVersion2();
      // }
    });

    migrationTransaction();
  }

  /**
   * 迁移到版本 1: 添加HTTP版本字段
   */
  migrateToVersion1() {
    console.log('📚 执行迁移: 添加HTTP版本字段...');

    // 检查并添加 requests 表的新字段
    const requestsColumns = this.db.prepare("PRAGMA table_info(requests)").all();
    const hasClientHttpVersion = requestsColumns.some(col => col.name === 'clientHttpVersion');
    const hasRemoteHttpVersion = requestsColumns.some(col => col.name === 'remoteHttpVersion');
    const hasTlsVersion = requestsColumns.some(col => col.name === 'tlsVersion');
    const hasClientIp = requestsColumns.some(col => col.name === 'clientIp');
    const hasRemoteIp = requestsColumns.some(col => col.name === 'remoteIp');

    if (!hasClientHttpVersion) {
      this.db.exec(`ALTER TABLE requests ADD COLUMN clientHttpVersion TEXT`);
      console.log('  ✅ 已添加 clientHttpVersion 字段到 requests 表');
    }

    if (!hasRemoteHttpVersion) {
      this.db.exec(`ALTER TABLE requests ADD COLUMN remoteHttpVersion TEXT`);
      console.log('  ✅ 已添加 remoteHttpVersion 字段到 requests 表');
    }

    if (!hasTlsVersion) {
      this.db.exec(`ALTER TABLE requests ADD COLUMN tlsVersion TEXT`);
      console.log('  ✅ 已添加 tlsVersion 字段到 requests 表');
    }

    if (!hasClientIp) {
      this.db.exec(`ALTER TABLE requests ADD COLUMN clientIp TEXT`);
      console.log('  ✅ 已添加 clientIp 字段到 requests 表');
    }

    if (!hasRemoteIp) {
      this.db.exec(`ALTER TABLE requests ADD COLUMN remoteIp TEXT`);
      console.log('  ✅ 已添加 remoteIp 字段到 requests 表');
    }

    // 检查并添加 responses 表的新字段
    const responsesColumns = this.db.prepare("PRAGMA table_info(responses)").all();
    const hasRemoteHttpVersionInResponses = responsesColumns.some(col => col.name === 'remoteHttpVersion');
    const hasTlsVersionInResponses = responsesColumns.some(col => col.name === 'tlsVersion');

    if (!hasRemoteHttpVersionInResponses) {
      this.db.exec(`ALTER TABLE responses ADD COLUMN remoteHttpVersion TEXT`);
      console.log('  ✅ 已添加 remoteHttpVersion 字段到 responses 表');
    }

    if (!hasTlsVersionInResponses) {
      this.db.exec(`ALTER TABLE responses ADD COLUMN tlsVersion TEXT`);
      console.log('  ✅ 已添加 tlsVersion 字段到 responses 表');
    }

    // 迁移现有数据
    this.migrateExistingData();
  }

  /**
   * 迁移现有数据
   */
  migrateExistingData() {
    // 迁移 requests 表的数据
    const requestsWithOldVersion = this.db.prepare(`
      SELECT COUNT(*) as count FROM requests 
      WHERE httpVersion IS NOT NULL AND clientHttpVersion IS NULL
    `).get();

    if (requestsWithOldVersion.count > 0) {
      this.db.exec(`
        UPDATE requests 
        SET clientHttpVersion = httpVersion 
        WHERE httpVersion IS NOT NULL AND clientHttpVersion IS NULL
      `);
      console.log(`  ✅ 已迁移 ${requestsWithOldVersion.count} 条请求记录的HTTP版本`);
    }

    // 迁移 responses 表的数据
    const responsesWithOldVersion = this.db.prepare(`
      SELECT COUNT(*) as count FROM responses 
      WHERE httpVersion IS NOT NULL AND remoteHttpVersion IS NULL
    `).get();

    if (responsesWithOldVersion.count > 0) {
      this.db.exec(`
        UPDATE responses 
        SET remoteHttpVersion = httpVersion 
        WHERE httpVersion IS NOT NULL AND remoteHttpVersion IS NULL
      `);
      console.log(`  ✅ 已迁移 ${responsesWithOldVersion.count} 条响应记录的HTTP版本`);
    }
  }

  /**
   * 回滚到指定版本（谨慎使用）
   */
  rollbackToVersion(targetVersion) {
    const currentVersion = this.getDatabaseVersion();
    
    if (targetVersion >= currentVersion) {
      console.log('📚 目标版本不低于当前版本，无需回滚');
      return;
    }

    console.warn(`⚠️ 即将回滚数据库版本: ${currentVersion} -> ${targetVersion}`);
    
    // 这里可以实现具体的回滚逻辑
    // 注意：SQLite 不支持 DROP COLUMN，所以回滚通常需要重建表
    
    this.setDatabaseVersion(targetVersion);
    console.log('📚 数据库版本回滚完成');
  }

  /**
   * 验证数据库结构
   */
  validateSchema() {
    const errors = [];

    try {
      // 验证必要的表是否存在
      const requiredTables = ['requests', 'responses', 'transactions', 'rules'];
      const existingTables = this.db.prepare(`
        SELECT name FROM sqlite_master 
        WHERE type='table' AND name NOT LIKE 'sqlite_%'
      `).all().map(row => row.name);

      for (const table of requiredTables) {
        if (!existingTables.includes(table)) {
          errors.push(`缺少必要的表: ${table}`);
        }
      }

      // 验证关键字段是否存在
      this.validateTableSchema('requests', [
        'id', 'url', 'method', 'timestamp', 'clientHttpVersion', 'remoteHttpVersion'
      ], errors);

      this.validateTableSchema('responses', [
        'id', 'requestId', 'statusCode', 'timestamp', 'remoteHttpVersion'
      ], errors);

      this.validateTableSchema('transactions', [
        'id', 'requestId', 'createdAt'
      ], errors);

      this.validateTableSchema('rules', [
        'id', 'name', 'enabled', 'conditions', 'actions'
      ], errors);

    } catch (error) {
      errors.push(`模式验证失败: ${error.message}`);
    }

    return {
      isValid: errors.length === 0,
      errors: errors
    };
  }

  /**
   * 验证表结构
   */
  validateTableSchema(tableName, requiredColumns, errors) {
    try {
      const columns = this.db.prepare(`PRAGMA table_info(${tableName})`).all();
      const columnNames = columns.map(col => col.name);

      for (const requiredColumn of requiredColumns) {
        if (!columnNames.includes(requiredColumn)) {
          errors.push(`表 ${tableName} 缺少字段: ${requiredColumn}`);
        }
      }
    } catch (error) {
      errors.push(`无法验证表 ${tableName}: ${error.message}`);
    }
  }

  /**
   * 获取迁移历史
   */
  getMigrationHistory() {
    return {
      currentVersion: this.getDatabaseVersion(),
      targetVersion: this.currentVersion,
      needsMigration: this.getDatabaseVersion() < this.currentVersion,
      schemaValidation: this.validateSchema()
    };
  }
} 